#!/usr/bin/python
# -*- coding:utf-8 -*-
__author__ = 'golsee'

from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, g
from flask.ext.login import login_required
from ..extensions import db
from ..models import User, Category, Article, Settings, Uploads, Blog_info, Comments
from .forms import AdminUserEditForm, CategoryForm, \
    CategoryeditForm, Admin_second_barForm, SettingsForm
from config import UPLOAD_FOLDER
from ..decorators import admin_required


@login_required
def index():
    if g.user.is_admin():
        flash(u'管理员登入')
    else:
        flash(u'普通权限登陆，不能更改任何东西')
    return render_template('admin/index.html')


@login_required
@admin_required
def users():
    users = User.query.all()
    return render_template('admin/users.html', users=users)


@login_required
@admin_required
def useredit(id):
    form = AdminUserEditForm()
    user = User.query.get(int(id))
    if form.validate_on_submit() and request.method == 'POST':
        user.is_locked = form.is_locked.data
        user.role = form.role.data
        db.session.add(user)
        db.session.commit()
        flash(u'已保存修改！')
        return redirect(url_for('admin.users'))
    else:
        form.is_locked.data = user.is_locked
        form.role.data = user.role
    return render_template('admin/useredit.html',
                           form=form, user=user)


@login_required
@admin_required
def userdelete(id):
    user = User.query.get(int(id))
    db.session.delete(user)
    db.session.commit()
    Blog_info.del_user()
    flash(u'删除成功！')
    return redirect(url_for('admin.users'))


@login_required
def category():
    category = Category.query.all()
    return render_template('admin/category.html', category=category)


@login_required
@admin_required
def categorycreate():
    if g.user.is_admin():
        form = CategoryForm(request.form)
        if request.method == 'POST' and form.validate():
            category = Category(name=form.name.data)
            category.createdate = datetime.now()
            if form.seq.data == None:
                category.seq = Category.default_seq()
            else:
                category.seq = form.seq.data
            db.session.add(category)
            db.session.commit()
            flash(u'类别已创建！')
            return redirect(url_for('admin.category'))
        return render_template('admin/categoryedit.html',
                               form=form)
    else:
        flash(u'无权限访问')
        return redirect(url_for('admin.index'))


@login_required
@admin_required
def categoryedit(id):
    form = CategoryeditForm()
    category = Category.query.get(int(id))
    if form.validate() and request.method == 'POST':
        category.name = form.name.data
        category.is_use = form.is_use.data
        category.seq = form.seq.data
        db.session.add(category)
        db.session.commit()
        flash(u'已保存修改！')
        return redirect(url_for('admin.category'))
    else:
        form.name.data = category.name
        form.is_use.data = category.is_use
        form.seq.data = category.seq
    return render_template('admin/categoryedit.html', form=form)


@login_required
@admin_required
def categorydelete(id):
    c = Category.query.get(int(id))
    db.session.delete(c)
    db.session.commit()
    flash(u'删除成功！')
    return redirect(url_for('admin.category'))


@login_required
def article():
    article = Article.article_all()
    return render_template('admin/article.html', article=article)


@login_required
@admin_required
def articledelete(id):
    article = Article.query.get(int(id))
    db.session.delete(article)
    db.session.commit()
    Blog_info.del_article()
    flash(u'删除成功！')
    return redirect(url_for('admin.article'))


@login_required
def admin_second_bar():
    bar = Settings.admin_second_bar()
    return render_template('admin/admin_second_bar.html', bar=bar)


@login_required
@admin_required
def admin_second_baredit(id):
    form = Admin_second_barForm()
    bar = Settings.query.get(int(id))
    if form.validate() and request.method == 'POST':
        bar.name = form.name.data
        bar.is_use = form.is_use.data
        bar.seq = form.seq.data
        bar.icon = form.icon.data
        bar.value = form.value.data
        db.session.add(bar)
        db.session.commit()
        flash(u'已保存修改！')
        return redirect(url_for('admin.admin_second_bar'))
    else:
        form.name.data = bar.name
        form.is_use.data = bar.is_use
        form.seq.data = bar.seq
        form.value.data = bar.value
        form.icon.data = bar.icon
    return render_template('admin/admin_second_baredit.html', form=form)


@login_required
@admin_required
def admin_second_baradd():
    form = Admin_second_barForm()
    if form.validate() and request.method == 'POST':
        bar = Settings()
        bar.name = form.name.data
        bar.is_use = form.is_use.data
        bar.seq = form.seq.data
        bar.icon = form.icon.data
        bar.type = 'admin_second_bar'
        bar.value = form.value.data
        db.session.add(bar)
        db.session.commit()
        flash(u'已保存修改！')
        return redirect(url_for('admin.admin_second_bar'))
    return render_template('admin/admin_second_baradd.html', form=form)


@login_required
def imgs():
    imgs = Uploads.get_imgs()
    return render_template('admin/imgs.html', imgs=imgs)


@login_required
def atts():
    atts = Uploads.get_atts()
    return render_template('admin/atts.html', atts=atts)


@login_required
def settings():
    form = SettingsForm()
    if form.validate_on_submit() and request.method == 'POST':
        if g.user.is_admin():
            for setting in Settings.blog_setting().keys():
                s = Settings.query.filter(Settings.type == setting, Settings.is_use == 1).first()
                f = 'form.%s.data' % str(setting)
                s.value = eval(f)
                db.session.add(s)
                db.session.commit()
                db.session.close()
            flash(u'保存成功')
            return redirect(url_for('admin.settings'))
        else:
            flash(u'无权限访问')
            return redirect(url_for('admin.settings'))
    else:
        settings = Settings.blog_setting()
        form.blog_name.data = settings['blog_name']
        form.MAIL_SERVER.data = settings['MAIL_SERVER']
        form.MAIL_PORT.data = settings['MAIL_PORT']
        form.MAIL_USE_SSL.data = settings['MAIL_USE_SSL']
        form.MAIL_USE_TLS.data = settings['MAIL_USE_TLS']
        form.MAIL_USERNAME.data = settings['MAIL_USERNAME']
        form.MAIL_PASSWORD.data = settings['MAIL_PASSWORD']
        form.DEFAULT_THEME.data = settings['DEFAULT_THEME']
        form.ADMIN.data = settings['ADMIN']
        return render_template('admin/settings.html', form=form)


@login_required
@admin_required
def rmfile(filename):
    import os

    florder = filename[:3]
    fileurl = os.path.join(UPLOAD_FOLDER, florder)
    realurl = os.path.join(fileurl, filename)
    f = Uploads.query.filter_by(file_name=filename).first()
    try:
        os.remove(realurl)
        flash(u'物理文件删除成功')
    except:
        flash(u'物理文件不存在')
    db.session.delete(f)
    db.session.commit()
    flash(u'数据删除成功')
    return redirect(url_for('admin.index'))


@login_required
def comments():
    comment = Comments.query.filter().all()
    return render_template('admin/comment.html', comment=comment)


@login_required
@admin_required
def comment_pass(id):
    comment = Comments.query.get(int(id))
    comment.disable = 1
    db.session.add(comment)
    db.session.commit()
    flash('审核成功')
    return redirect(url_for('admin.comments'))


@login_required
@admin_required
def comment_disable(id):
    comment = Comments.query.get(int(id))
    comment.disable = 2
    db.session.add(comment)
    db.session.commit()
    flash('操作成功')
    return redirect(url_for('admin.comments'))
